import { Radio, Input, Button, Space, Card, Tooltip } from 'antd';
import './Slider.css';
import { useState } from 'react';
import { SyncOutlined } from '@ant-design/icons';
import http from '../services/api';
import { message } from 'antd';
import { SizeMap } from '../types/components/slider';
import { ImageGenerationResponse } from '../types/api/image';

export default function Slider() {
  const [model, setModel] = useState('wanx2.1-t2i-turbo');
  const [prompt, setPrompt] = useState('');
  const [size, setSize] = useState('1024*1024');
  const [n, setN] = useState(1);
  const [currentPromptIndex, setCurrentPromptIndex] = useState(0);

  const handleGenerate = async () => {
    const requestData = {
      model,
      input: {
        prompt
      },
      parameters: {
        size,
        n
      }
    };

    try {
      const response = await http.post<ImageGenerationResponse>('/services/aigc/text2image/image-synthesis', requestData, {
        headers: {
          'X-DashScope-Async': 'enable',
          'Authorization': `Bearer ${import.meta.env.VITE_API_KEY}`
        }
      });
      
      // 将task_id存储到sessionStorage
      if (response.output?.task_id) {
        sessionStorage.setItem('task_id', response.output.task_id);
        window.dispatchEvent(new CustomEvent('taskIdChanged'));
      }
    } catch (error: any) {
      console.error('生成失败:', error);
      if (error.response?.data?.code === 'InvalidApiKey') {
        message.error('API密钥无效，请检查您的API密钥配置');
      } else {
        message.error('生成失败，请稍后重试');
      }
    }
  };

  const sizeMap: SizeMap = {
    size1: '1024*1024',
    size2: '1280*720',
    size3: '720*1280',
    size4: '1280*960',
    size5: '960*1280'
  };

  const examplePrompts = [
    "阳光明媚的下午，咖啡馆里飘着咖啡香",
    "未来城市夜景，霓虹灯闪烁，飞行汽车穿梭",
    "童话风格的森林小屋，周围开满鲜花"
  ];

  const handlePromptClick = (prompt: string) => {
    setPrompt(prev => prev ? `${prev}, ${prompt}` : prompt);
  };

  const handleRefreshPrompt = () => {
    setCurrentPromptIndex(prev => (prev + 1) % examplePrompts.length);
  };

  // 移除useEffect定时器代码

  return (
    <div className="slider">
      <Space direction="vertical" size="large" style={{ width: '100%', maxWidth: '800px', margin: '0 auto' }}>
        {/* 模型选择 */}
        <Card title="模型选择">
          <Radio.Group
            defaultValue="model1"
            onChange={(e) => setModel(e.target.value === 'model1' ? 'wanx2.1-t2i-turbo' : e.target.value === 'model2' ? 'wanx2.1-t2i-plus' : 'wanx2.0-t2i-turbo')}
          >
            <Tooltip title="生成速度更快，通用生成模型">
              <Radio.Button value="model1">wanx2.1-t2i-turbo</Radio.Button>
            </Tooltip>
            <Tooltip title="生成图像细节更丰富，速度稍慢，通用生成模型">
              <Radio.Button value="model2">wanx2.1-t2i-plus</Radio.Button>
            </Tooltip>
            <Tooltip title="擅长质感人像与创意设计，速度中等，性价比高">
              <Radio.Button value="model3">wanx2.0-t2i-turbo</Radio.Button>
            </Tooltip>
          </Radio.Group>
        </Card>

        {/* 文本输入框 */}
        <Card title="文本输入">
          <Input.TextArea
            rows={4}
            placeholder="试试输入你心中的画面，尽量描述具体，可以尝试用一些风格修饰词辅助你的表达"
            style={{ width: '100%' }}
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
          />
          <div style={{ marginTop: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
            <Button
              type="dashed"
              size="small"
              onClick={() => handlePromptClick(examplePrompts[currentPromptIndex])}
            >
              {examplePrompts[currentPromptIndex]}
            </Button>
            <Button
              type="text"
              icon={<SyncOutlined />}
              onClick={handleRefreshPrompt}
              style={{ padding: '4px' }}
            />
          </div>
        </Card>

        {/* 照片尺寸选择 */}
        <Card title="照片尺寸">
          <Radio.Group
            defaultValue="size1"
            style={{ width: '100%' }}
            onChange={(e) => {
              const value = e.target.value as keyof SizeMap;
              setSize(sizeMap[value]);
            }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Radio value="size1">1:1</Radio>
              <Radio value="size2">16:9</Radio>
              <Radio value="size3">9:16</Radio>
              <Radio value="size4">4:3</Radio>
              <Radio value="size5">3:4</Radio>
            </div>
          </Radio.Group>
        </Card>

        {/* 照片数量选择 */}
        <Card title="照片数量" className="photo-count-selector">
          <Radio.Group
            defaultValue="num1"
            style={{ width: '100%' }}
            onChange={(e) => setN(Number(e.target.value.replace('num', '')))}
          >
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(4, 1fr)',
              gap: '8px'
            }}>
              <Radio.Button
                value="num1"
                style={{ textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >
                1张
              </Radio.Button>
              <Radio.Button
                value="num2"
                style={{ textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >
                2张
              </Radio.Button>
              <Radio.Button
                value="num3"
                style={{ textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >
                3张
              </Radio.Button>
              <Radio.Button
                value="num4"
                style={{ textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
              >
                4张
              </Radio.Button>
            </div>
          </Radio.Group>
        </Card>

        {/* 开始按钮 */}
        <Button
          type="primary"
          size="large"
          style={{ width: '100%', height: '50px', fontSize: '18px' }}
          onClick={handleGenerate}
          disabled={!prompt.trim()} // 添加disabled属性
        >
          开始生成
        </Button>
      </Space>
    </div>
  );
}
